package ch.rheintalconnection.sysventory.businessServices;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import ch.rheintalconnection.sysventory.domain.Scan;
import ch.rheintalconnection.sysventory.domain.ScanEntry;
import ch.rheintalconnection.sysventory.domain.User;
import ch.rheintalconnection.sysventory.foundation.Time;
import ch.rheintalconnection.sysventory.technicalServices.IDataReader;
import ch.rheintalconnection.sysventory.technicalServices.IHostScanner;
import ch.rheintalconnection.sysventory.technicalServices.IIpScanner;

public class NetworkScanner {

	private IIpScanner ipScanner;
	private IDataReader dataReader;
	
	private static Logger logger = LogManager.getLogger(NetworkScanner.class);

	public NetworkScanner(IIpScanner ipScanner, IDataReader dataReader) {
		super();
		this.ipScanner = ipScanner;
		this.dataReader = dataReader;
	}

	public Scan scan(String ipmask, User user) {

		Timestamp startDate = Time.now();

		List<ScanEntry> scanEntrys = new ArrayList<ScanEntry>();

		List<IHostScanner> hostScanners = ipScanner.scanIps(ipmask);

		ExecutorService executor = Executors.newFixedThreadPool(hostScanners.size());
		List<FutureTask<ScanEntry>> taskList = new ArrayList<FutureTask<ScanEntry>>();

		for (IHostScanner hostScanner : hostScanners) {
			
			DomainHostScanner domainHostScanner = new DomainHostScanner(hostScanner, dataReader);
			FutureTask<ScanEntry> futureTask = new FutureTask<ScanEntry>(domainHostScanner);
			taskList.add(futureTask);
			executor.execute(futureTask);
		}
		
		 for (FutureTask<ScanEntry> futureTask : taskList) {
				
	        	try {
	        		ScanEntry scanEntry = futureTask.get();
	        		scanEntrys.add(scanEntry);

					
				} catch (Exception e) {
					logger.error("Beim Scannen eines Hosts ist ein Fehler aufgetreten", e);
				} 
			}
	        executor.shutdown();

		Timestamp endDate = Time.now();

		return new Scan(startDate, endDate, user, scanEntrys);
	}

}
